var _class, _temp;

import Taro from '@tarojs/taro-rn';
import * as tslib_1 from "tslib";
import React from 'react';
import { Component } from "@tarojs/taro-rn";
import { View, Image, Text, ScrollView } from "@tarojs/components-rn";
import { toJS } from 'mobx';
import { inject, observer } from "@tarojs/mobx-rn";
import { getRuntime, pageSize, subtime } from "../../utils/common";
import orderStyleSheet from "./order_styles";
var _styleSheet = orderStyleSheet;

function _getClassName() {
  var className = [];
  var args = arguments[0];
  var type = Object.prototype.toString.call(args).slice(8, -1).toLowerCase();

  if (type === 'string') {
    args = args.trim();
    args && className.push(args);
  } else if (type === 'array') {
    args.forEach(function (cls) {
      cls = _getClassName(cls).trim();
      cls && className.push(cls);
    });
  } else if (type === 'object') {
    for (var k in args) {
      k = k.trim();

      if (k && args.hasOwnProperty(k) && args[k]) {
        className.push(k);
      }
    }
  }

  return className.join(' ').trim();
}

function _getStyle(classNameExpression) {
  var className = _getClassName(classNameExpression);

  var classNameArr = className.split(/\s+/);
  var style = [];

  if (classNameArr.length === 1) {
    style.push(_styleSheet[classNameArr[0].trim()]);
  } else {
    classNameArr.forEach(function (cls) {
      style.push(_styleSheet[cls.trim()]);
    });
  }

  return style;
}

let Order = (_temp = _class = class Order extends Component {
  constructor(props) {
    super(props);
    this.state = {
      orderState: [{ id: 0, name: '全部' }, { id: 1, name: '待付款' }, { id: 2, name: '待发货' }, { id: 3, name: '待收货' }, { id: 4, name: '已完成' }],
      currentState: 0,
      totalCount: 0,
      items: [],
      pageIndex: 1,
      pageSize
    };
  }
  componentWillMount() {
    Taro.setNavigationBarTitle({ title: '我的订单' });
    this.getOrders();
  }
  changeCurrentState(currentState) {
    this.setState({
      currentState,
      items: [],
      pageIndex: 1
    }, () => {
      this.getOrders();
    });
  }
  getOrders() {
    let { PointMallStore } = this.props.stores;
    let { pageIndex, pageSize, currentState } = this.state;
    PointMallStore.getOrders({
      formStatus: currentState === 0 ? null : currentState,
      pageIndex,
      pageSize,
      callback: res => {
        res.items && res.items.map(item => {
          let orderLimiTime = this.getLimitTime(item.creationTime);
          return item.orderLimiTime = orderLimiTime;
        });
        if (pageIndex === 1) {
          this.setState({ totalCount: toJS(res.totalCount), items: toJS(res.items) });
        } else {
          const { items } = this.state;
          items.push(...(res.items || []));
          this.setState({ totalCount: res.totalCount, items });
        }
      }
    });
  }
  // 计算订单有效期倒计时(有效期为24小时)
  getLimitTime(time) {
    // 有效期减去现在时间就是订单剩余时间
    let now = new Date();
    let dayStamp = 86400000; // 一天的时间戳(毫秒数)
    let orderTime = new Date(time).getTime(); // 订单创建时间
    let orderLimitTime = orderTime + dayStamp; // 订单有效期
    let nowTimeStamp = now.getTime(); // 现在的时间戳
    let inteval = orderLimitTime - nowTimeStamp; // 订单剩余时间
    let hoursTamp = 3600000;
    let hours = Math.floor(inteval / hoursTamp);
    let minStamp = inteval % hoursTamp;
    let min = Math.floor(minStamp / 60000);
    if (hours < 0) {
      return '订单已失效';
    }
    return `${hours}小时${min}分钟后订单将关闭`;
  }
  // 取消订单
  cancelOrdedr(id) {
    if (!id) {
      getRuntime().showToast('参数错误~');
      return;
    }
    Taro.showModal({
      title: '你确定要取消订单吗?',
      content: '',
      cancelText: '再想想',
      confirmText: '确认取消'
    }).then(res => {
      if (res.confirm) {
        let { PointMallStore } = this.props.stores;
        PointMallStore.cancelOrder({
          form: { id },
          callback: () => {
            getRuntime().showToast('取消订单成功~');
          }
        });
      }
    });
  }
  // 删除订单
  delOrder(id) {
    if (!id) {
      getRuntime().showToast('参数错误~');
      return;
    }
    Taro.showModal({
      title: '你确定要删除订单吗?',
      content: '',
      cancelText: '再想想',
      confirmText: '确认删除'
    }).then(res => {
      if (res.confirm) {
        let { PointMallStore } = this.props.stores;
        PointMallStore.deleteOrder({
          form: { id },
          callback: () => {
            getRuntime().showToast('删除订单成功~');
          }
        });
      }
    });
  }
  // 确认收货
  confirmGet(id) {
    if (!id) {
      getRuntime().showToast('参数错误~');
      return;
    }
    let { PointMallStore } = this.props.stores;
    PointMallStore.confirmGet({
      form: { id },
      callback: () => {
        getRuntime().showToast('收货成功~');
      }
    });
  }
  // 再来一单
  againOrder(item) {
    if (!item.id) {
      getRuntime().showToast('参数错误~');
      return;
    }
    //console.log(item)
    let userCart = {
      freight: item.freight,
      itemId: item.orderDetails[0]['itemId'],
      itemNum: item.orderDetails[0]['qty'],
      itemSignPrice: item.orderDetails[0]['price'],
      itemPrice: item.orderDetails[0]['totalPrice'],
      itemSpec: item.orderDetails[0]['spec'],
      name: item.orderDetails[0]['name'],
      picture: item.orderDetails[0]['picture'],
      publicDonations: item.gyMoney || 0,
      pointValue: item.pointValue || 0,
      specNo: '',
      specNoId: item.orderDetails[0]['itemSpecId']
    };
    //console.log(userCart)
    getRuntime().setStorage('userCart', userCart);
    getRuntime().navigateTo('/pages/mall/order_confirm?id=' + item.orderDetails[0]['itemId']);
    /*let { PointMallStore } = this.props.stores
    PointMallStore.placeNewOrder({
      item.id,
      callback: res => {
        // let payParams = JSON.parse(res.payParams)
        getRuntime().wxPay(res,() => {
          getRuntime().navigateTo(`/pages/user/order_pay_success?id=${id}`)
        })
      }
    })*/
  }
  // 立即支付
  pay(id) {
    if (!id) {
      getRuntime().showToast('参数错误~');
      return;
    }
    let { PointMallStore } = this.props.stores;
    PointMallStore.pay({
      form: {
        orderId: id,
        payType: '1',
        isPayPoints: false
      },
      callback: res => {
        // let payParams = JSON.parse(res.payParams)
        getRuntime().wxPay(res, () => {
          getRuntime().navigateTo(`/pages/user/order_pay_success?id=${id}`);
        });
      }
    });
  }
  onReachBottom() {
    let { totalCount, pageSize, pageIndex } = this.state;
    const { loading } = this.props.stores.homeStore;
    if (totalCount > pageIndex * pageSize && !loading) {
      this.setState({
        pageIndex: pageIndex + 1
      }, () => {
        this.getOrders();
      });
    }
  }
  handelRouter(url = '/pages/index/index') {
    getRuntime().navigateTo(url);
  }
  render() {
    let { orderState, currentState, items } = this.state;
    return <View style={[_styleSheet["my-order-detail"], _styleSheet["my-order"]]}>
        <ScrollView scrollX={true} style={_styleSheet["scroll-view-nav"]}>
          {orderState.map(item => {
          return <View key={item.id} onClick={this.changeCurrentState.bind(this, item.id)} style={_getStyle(currentState === item.id ? 'scroll-item scroll-item-on' : 'scroll-item')}>{item.name}<Text style={_styleSheet["line"]} /></View>;
        })}
        </ScrollView>

        <View style={_styleSheet["my-order-wrap"]}>
          {items.length > 0 && items.map(item => {
          let tpl = null;
          let tplCommon = <View onClick={this.handelRouter.bind(this, '/pages/user/order_detail?id=' + item.id)}>
                    <View style={_styleSheet["time-status"]}>
                      <View style={_styleSheet["list-info"]}>{subtime(item.creationTime)}</View>
                      <View style={[_styleSheet["list-title"], _styleSheet["color-orange"]]}>{item.statusView}</View>
                    </View>
                    <View style={_styleSheet["order-spec"]}>
                      <View style={_styleSheet["l"]}>
                        <Image src={item.orderDetails[0]['picture']} style={_styleSheet["img"]} />
                        <View style={_styleSheet["info"]}>
                          <View style={_styleSheet["list-title"]}>{item.orderDetails[0]['name']}</View>
                          <View style={_styleSheet["list-info"]}>
                            
                            {item.orderDetails[0]['spec']}
                          </View>
                        </View>
                      </View>
                      <View style={_styleSheet["r"]}>
                        <View style={_styleSheet["list-price"]}>
                          <Text style={_styleSheet["list-small"]}>￥</Text>{item.orderDetails[0]['totalPrice']}</View>
                        <View style={[_styleSheet["list-info"], { textAlign: 'right' }]}>
                          <Text>x{item.orderDetails[0]['qty']}</Text>
                        </View>
                      </View>
                    </View>
                 </View>;
          // 待付款
          if (item.status === 1) {
            tpl = <View style={_styleSheet["order-item"]}>
                        {tplCommon}
                        <View style={[_styleSheet["line"], _styleSheet["undelive"]]}>
                          <View style={_styleSheet["list-title"]}> </View>
                          <View style={[_styleSheet["money"], _styleSheet["color-orange"]]}><Text style={_styleSheet["list-title"]}>共{item.orderDetails[0]['qty']}件商品 应付款：</Text><Text style={_styleSheet["list-small"]}>￥</Text>{item.actualAmount}</View>
                        </View>
                      

                        <View style={[_styleSheet["line"], _styleSheet["line2"]]}>
                          <View style={[_styleSheet["list-desc"], _styleSheet["l"]]}>{item.orderLimiTime}</View>
                          <View style={_styleSheet["r"]}>
                            <View onClick={this.cancelOrdedr.bind(this, item.id)} style={_styleSheet["btn"]}>取消订单</View>
                            <View onClick={this.pay.bind(this, item.id)} style={[_styleSheet["btn"], _styleSheet["btn-submit"]]}>立即付款</View>
                          </View>
                        </View>
                      </View>;
          }
          // 待发货
          if (item.status === 2) {
            tpl = <View style={_styleSheet["order-item"]}>
                      {tplCommon}
                      <View style={[_styleSheet["line"], _styleSheet["undelive"]]}>
                        <View style={_styleSheet["list-title"]}> </View>
                        <View style={[_styleSheet["money"], _styleSheet["color-orange"]]}><Text style={_styleSheet["list-title"]}>共{item.orderDetails[0]['qty']}件商品 应付款：</Text><Text style={_styleSheet["list-small"]}>￥</Text>{item.actualAmount}</View>
                      </View>
                    </View>;
          }
          // 待收货
          if (item.status === 3) {
            tpl = <View style={_styleSheet["order-item"]}>
                      {tplCommon}
                      <View style={_styleSheet["line"]}>
                        <View style={_styleSheet["list-title"]}>订单金额</View>
                        <View style={[_styleSheet["money"], _styleSheet["color-orange"]]}><Text style={_styleSheet["list-small"]}>￥</Text>{item.actualAmount}</View>
                      </View>

                      <View style={[_styleSheet["line"], _styleSheet["line2"]]}>
                        <View style={[_styleSheet["list-desc"], _styleSheet["color-blue"]]}>运单号：{item.shippingNo}</View>
                        <View onClick={this.confirmGet.bind(this, item.id)} style={_styleSheet["btn"]}>确认收货</View>
                      </View>
                    </View>;
          }
          // 待评价
          if (item.status === 4) {
            tpl = <View style={_styleSheet["order-item"]}>
                      {tplCommon}
                      <View style={_styleSheet["line"]}>
                        <View style={_styleSheet["list-title"]}>订单金额</View>
                        <View style={[_styleSheet["money"], _styleSheet["color-orange"]]}><Text style={_styleSheet["list-small"]}>￥</Text>{item.actualAmount}</View>
                      </View>

                      <View style={[_styleSheet["line"], _styleSheet["line2"]]}>
                        <View style={_styleSheet["l"]} />
                        <View style={_styleSheet["r"]}>
                          <View onClick={this.delOrder.bind(this, item.id)} style={_styleSheet["btn"]}>删除订单</View>
                          <View onClick={this.againOrder.bind(this, item)} style={[_styleSheet["btn"], _styleSheet["btn-active"]]}>再次购买</View>
                        </View>
                      </View>
                    </View>;
          }
          return tpl;
        })}
          {items.length <= 0 && <View style={_styleSheet["from-footer"]}>你还没有订单哦~</View>}
        </View>

      </View>;
  }
}, _class.config = {
  navigationBarTitleText: '我的订单'
}, _temp);
Order = tslib_1.__decorate([inject("stores"), observer], Order);
export default Order;